<template>
  <div class="app-container">
    <div class="p4">
      <FaSearchBar :show-toggle="false">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="任务名称" prop="jobName">
            <el-input v-model="queryParams.jobName" placeholder="请输入任务名称" clearable style="width: 150px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="组名" prop="groupName">
            <el-input v-model="queryParams.groupName" placeholder="请输入组名" clearable style="width: 150px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
              <el-option v-for="dict in job_status" :key="dict.value" :label="dict.label" :value="Number(dict.value)"
                @change="handleQuery" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </FaSearchBar>
      <el-divider border-style="dashed" style="margin:0px 0px 20px 0px" />

      <el-space wrap>
        <el-button type="primary" icon="Plus" @click="handleAdd" v.auth="['job$add']">新增</el-button>
        <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete"
          v.auth="['job$remove']">删除</el-button>
        <el-button type="warning" icon="Download" @click="handleExport" v.auth="['job$export']">导出</el-button>
      </el-space>

      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" stripe
        highlight-current-row border class="mt4">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="#" align="center" prop="id" /> -->
        <el-table-column label="任务名称" prop="jobName" :show-overflow-tooltip="true" width="150px" />
        <el-table-column label="任务组名" align="center" prop="jobGroup" width="100px" />
        <el-table-column label="执行类" prop="jobClass" :show-overflow-tooltip="true" width="280px" />
        <el-table-column label="状态" align="center" prop="status" width="100px">
          <template #default="scope">
            <DictTag :dictData="job_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="Cron表达式" align="center" prop="cron" width="120px" />
        <el-table-column label="策略" align="center" prop="misfirePolicy" width="100px">
          <template #default="scope">
            <DictTag :dictData="job_misfire_policy" :value="scope.row.misfirePolicy" />
          </template>
        </el-table-column>
        <el-table-column label="并发" align="center" prop="concurrent" width="100px">
          <template #default="scope">
            <DictTag :dictData="job_concurrent" :value="scope.row.concurrent" />
          </template>
        </el-table-column>
        <el-table-column label="失败重试次数" align="center" prop="retryCount" width="120px" />
        <el-table-column label="超时时间（秒）" align="center" prop="execTimeout" width="140px" />
        <el-table-column label="最后执行时间" align="center" prop="lastExecAt" width="180px" />
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <!-- <el-table-column label="创建者" align="center" prop="createdBy" /> -->
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180px" />
        <el-table-column align="center" width="320px" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button size="small" plain type="primary" @click="handleLog(scope.row)" v.auth="['job:log$list']">日志
            </el-button>
            <el-button size="small" plain type="primary" @click="handleManualExecute(scope.row)"
              v.auth="['job$manual']">手动执行
            </el-button>
            <el-button size="small" plain type="success" icon="Edit" @click="handleUpdate(scope.row)"
              v.auth="['job$edit']">修改
            </el-button>
            <el-button size="small" plain type="danger" icon="Delete" @click="handleDelete(scope.row)"
              v.auth="['job$remove']">删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="loadData" />
    </div>
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="sysJobRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="form.jobName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务组名" prop="jobGroup">
          <el-input v-model="form.jobGroup" placeholder="请输入任务组名" />
        </el-form-item>
        <el-form-item prop="jobClass">
          <template #label>
            <span>
              执行类
              <el-tooltip content='执行类，如：`com.easy.module.quartz.job.TestJob`' placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-input v-model="form.jobClass" placeholder="请输入执行类全路径" />
        </el-form-item>
        <el-form-item prop="cron">
          <template #label>
            <span>
              Cron表达式
              <el-tooltip content='Cron表达式，如：`* * * * * ? *`' placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-input v-model="form.cron" placeholder="请输入Cron表达式" />
        </el-form-item>
        <el-form-item prop="jobParams">
          <template #label>
            <span>
              任务参数
              <el-tooltip content='任务参数（JSON 格式）' placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-input v-model="form.jobParams" placeholder="请输入任务参数（JSON 格式）" />
        </el-form-item>
        <el-form-item prop="retryCount">
          <template #label>
            <span>
              失败重试次数
              <el-tooltip content='失败重试次数（0-5 次）' placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-input-number :min="0" :max="5" v-model="form.retryCount" />
        </el-form-item>
        <el-form-item prop="execTimeout">
          <template #label>
            <span>
              超时时间（秒）
              <el-tooltip content='超时时间（秒），0 表示无超时限制' placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-input-number :min="0" v-model="form.execTimeout" placeholder="请输入超时时间" />
        </el-form-item>
        <el-form-item label="策略" prop="misfirePolicy">
          <template #label>
            <span>
              策略
              <el-tooltip placement="top">
                <template #content>
                  <div>
                    触发续跑: 补最近 1 次，恢复正常周期<br />
                    自然续跑: 忽略错过，恢复正常周期<br />
                    全量回溯: 补所有错过，恢复正常周期<br />
                  </div>
                </template>
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-select v-model="form.misfirePolicy" placeholder="请选择策略" clearable style="width: 150px">
            <el-option v-for="dict in job_misfire_policy" :key="dict.value" :label="dict.label"
              :value="Number(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="并发" prop="concurrent">
          <el-radio-group v-model="form.concurrent">
            <el-radio v-for="dict in job_concurrent" :key="dict.value" :label="Number(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" :rows="3" type="textarea" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in job_status" :key="dict.value" :label="Number(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysJob">
import apiSysJob from "@/api/tool/job";
import router from "@/router";

import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance();


const { job_status, job_misfire_policy, job_concurrent } = proxy.useDict('job_status', 'job_misfire_policy', 'job_concurrent');

const userStore = useUserStore();
const { } = proxy.useDict();
const dataList = ref([]);
const open = ref(false);
const loading = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    jobName: undefined,
    groupName: undefined,
    status: undefined,
  },
  rules: {
    jobName: [{ required: true, message: "任务名称不允许为空", trigger: "blur" }],
    jobGroup: [{ required: true, message: "任务组名不允许为空", trigger: "blur" }],
    jobClass: [{ required: true, message: "执行类不允许为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不允许为空", trigger: "blur" }],
    cron: [{ required: true, message: "Cron表达式不允许为空", trigger: "blur" }],
    retryCount: [{ required: true, message: "失败重试次数不允许为空", trigger: "blur" }],
    execTimeout: [{ required: true, message: "超时时间不允许为空", trigger: "blur" }],
    misfirePolicy: [{ required: true, message: "策略不允许为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);


/**
 * 加载数据
 */
function loadData() {
  // loading.value = true;
  apiSysJob.page(queryParams.value).then(response => {
    dataList.value = response.data.rows;
    total.value = response.data.total;
    // loading.value = false;
  });
}

/**
 * 关闭窗口
 */
function cancel() {
  open.value = false;
  reset();
}

/**
 * 重置表单
 */
function reset() {
  form.value = {
    id: undefined,
    jobName: undefined,
    jobGroup: 'DEFAULT',
    jobClass: undefined,
    cron: undefined,
    misfirePolicy: 2,
    concurrent: 0,
    remark: undefined,
    jobParams: undefined,
    retryCount: 0,
    execTimeout: 300,
    status: 0,
  };
  proxy.resetForm("sysJobRef");
}

/**
 * 搜索
 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  loadData();
}

/**
 * 重置查询表单
 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/**
 * 选中操作
 * @param selection 选中数据
 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/**
 * 新增操作
 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增定时任务";
}

/**
 * 更新操作
 * @param row 数据行
 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  apiSysJob.getById(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改定时任务";
  });
}

function handleLog(row) {
  router.push({ path: '/tool/job/log', query: { jobId: row.id } })
}


/**
 * 提交定时任务数据
 */
function submitForm() {
  proxy.$refs["sysJobRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        apiSysJob.update(form.value).then(response => {
          proxy.$modal.success("修改成功");
          open.value = false;
          loadData();
        });
      } else {
        apiSysJob.add(form.value).then(response => {
          proxy.$modal.success("新增成功");
          open.value = false;
          loadData();
        });
      }
    }
  });
}

/**
 * 删除定时任务数据
 * @param row 数据行
 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除任务编号为"' + _ids + '"的任务吗？').then(function () {
    return apiSysJob.delete(_ids);
  }).then(() => {
    loadData();
    proxy.$modal.success("删除成功");
  }).catch(() => { });
}

/**
 * 导出Excel
 */
function handleExport() {
  apiSysJob.download(queryParams.value, "定时任务");
}


function handleManualExecute(row) {
  proxy.$modal.confirm('是否确认手动执行编号为"' + row.id + '"的任务吗？').then(function () {
    return apiSysJob.manualExecute(row.id);
  }).then(() => {
    proxy.$modal.success("手动执行成功");
  }).catch(() => { });
}

loadData();
</script>
